#import "MEvaluation.h"
#import "MPacket.h"

@implementation MEvaluation

- (id) initWithEvaluator: (MEvaluator*) evaluator expr: (MExpr*) expr
{
	NSParameterAssert(evaluator);
	NSParameterAssert(expr);
	
	self = [super init];
	_evaluator = evaluator;
	_expr = [expr retain];
	return self;
}

- (void) dealloc
{
	[_expr release];
	[_result release];
	[_inputName release];
	[_packets release];
	[super dealloc];
}

- (MEvaluator*) evaluator
{
	return _evaluator;
}

- (MExpr*) expr
{
	return _expr;
}

- (MExpr*) result
{
	return _result;
}

- (void) setResult: (MExpr*) result
{
	[_result autorelease];
	_result = [result retain];
}

- (NSString*) inputName
{
	return _inputName;
}

- (void) setInputName: (NSString*) inputName
{
	[_inputName autorelease];
	_inputName = [inputName retain];
}

- (void) addPacket: (MPacket*) packet
{
	if(_packets == nil)
		_packets = [[NSMutableArray alloc] init];
	
	if(![_packets containsObject: packet])
		[_packets addObject: packet];
}

- (MDisplayPacket*) currentDisplayPacketCreating: (BOOL) creating
{
	int count = [_packets count], i;
	for(i = count - 1; i >= 0; i--)
	{
		if([[_packets objectAtIndex: i] isKindOfClass: [MDisplayPacket class]])
		{
			MDisplayPacket* pkt = [_packets objectAtIndex: i];
			if(![pkt isEnded])
				return pkt;
			break;
		}
	}
	if(creating)
	{
		MDisplayPacket* pkt = [[[MDisplayPacket alloc] initWithData: @""] autorelease];
		[_packets addObject: pkt];
		return pkt;
	}
	return nil;
}

@end
